<?php

namespace catchAdmin\externalGoods\service;

use catchAdmin\externalGoods\model\Category;
use catchAdmin\externalGoods\model\TenantGoods as tenantGoodsModel;
use catchAdmin\externalGoods\model\TenantGoodsAttr as tenantGoodsAttrModel;
use catchAdmin\externalGoods\model\TenantGoodsRule as tenantGoodsRuleModel;
use think\facade\Request;
use catchAdmin\externalGoods\model\Goods as externalGoodsModel;
use catchAdmin\externalGoods\model\GoodsRule as externalGoodsRuleModel;
use catchAdmin\externalGoods\model\GoodsAttribute as externalGoodsAttribute;
use catcher\CatchAuth;
use catcher\CatchResponse;
use catcher\Code;
use houniao\api\v1\Goods;
use think\Exception;
use think\facade\Db;
use catchAdmin\externalGoods\model\GoodsCustoms as GoodsCustomerModel;

class GoodsService{

    protected $user;
    protected $price_fl = 1.1;

    protected $tenantList =  [
        ['tenant_id'=>'10043'],
        ['tenant_id'=>'10050'],
//        ['tenant_id'=>'10143'],
        ['tenant_id'=>'10144'],
        ['tenant_id'=>'10146'],
        ['tenant_id'=>'10147'],
        ['tenant_id'=>'10159'],//果然便宜
        ['tenant_id'=>'10161'],//文商跨境
        ['tenant_id'=>'10170']//深圳东九
    ];

    public function __construct()
    {
        $request_url = Request::url();

        if($request_url == '/callback/houniao' || $request_url == '/callback/xyb2b'){
            $this->user  = (new \catchAdmin\permissions\model\Users())->find(1);
        }elseif ($request_url == 'http://localhost'){
            $this->user  = (new \catchAdmin\permissions\model\Users())->find(1);
        }else{
            $user = (new CatchAuth())->user();
            $this->user = $user;
        }
    }

    //远程和本地数据简单对比
    public function check($param){
        $user = (new CatchAuth())->user();
        $this->user = $user;
        //远程数据
        $pages = $param['pages'];
        $data = $param['data'];

        if(0 == $pages['total']){
            return CatchResponse::fail('total:0');
        }

        //远程商品本地商品对比
        $data =  $this->remoteLocalCheck(['goods_data'=>$data],'all')['goods_data'];

        return json([
            'code'    => Code::SUCCESS,
            'message' => 'success',
            'count'   => $pages['total'],
            'current' => $pages['current_page'],
            'limit'   => $pages['page_size'],
            'data'    => $data
        ]);
    }

    //同步
    public function sync($param){
//        $user = (new CatchAuth())->user();
//        $this->user = $user;
//        $this->user  = (new \catchAdmin\permissions\model\Users())->find(1);

//        var_dump($param);die();

//        $a =  (new Goods())->goodsSpecPrice([
//            'goods_spu'=>'HW00032837']);
//        dd($a);

        if(empty($param)){
            return CatchResponse::fail('没有数据');
        }
        $data['goods_data'] = $param;

        Db::startTrans();
        try {
            //远程商品本地商品对比
            $data =  $this->remoteLocalCheck($data);

            //批量商品添加&修改
            $data =  $this->batchDealGoods($data);

            //商品属性和规格获取
            $data = $this->batchGetGoodsAttr($data);

            //商品属性添加&修改
            $data =  $this->batchDealGoodsAttr($data);

            //商品规格 sku 添加&修改
            $data = $this->batchDealGoodsRule($data,1);



            Db::commit();
            return CatchResponse::success();
        } catch (\Exception $exception) {
            Db::rollback();
            return CatchResponse::fail('同步失败' . json_encode($exception->getTrace()));
        }
    }

    public function array_flatten($array,$key = 'children') {

        $result = [];
        foreach ($array as $k1 => &$v1) {
            $v1['level'] = 1;
            $result[] = $v1;
            if(!array_key_exists($key,$v1) || empty($v1[$key])){
                continue;
            }

            foreach ($v1[$key] as $k2 => &$v2){
                $v2['level'] = 2;
                $result[] = $v2;
                if(!array_key_exists($key,$v2) || empty($v2[$key])){
                    continue;
                }

                foreach ($v2[$key] as $k3 => &$v3){
                    $v3['level'] = 3;
                    $result[] = $v3;
                }
            }

        }
        return $result;
    }

    public function makeTree($data)
    {

        $res = [];
        $tree = [];

        // 整理数组
        foreach ($data as $key => $vo) {
            $res[$vo['id']] = $vo;
        }
        unset($data);

        // 查询子孙
        foreach ($res as $key => $vo) {
            if ($vo['pid'] != 0) {
                $res[$vo['pid']]['child'][] = &$res[$key];
            }
        }

        // 去除杂质
        foreach ($res as $key => $vo) {
            if ($vo['pid'] == 0) {
                $tree[] = $vo;
            }
        }
        unset($res);

        return $tree;
    }

    public function generateTree($data,$parent_id = 0)
    {
        $tree = [];
        $newData = array_combine(array_column($data,'id'),$data);

        foreach ($newData as $key => $datum) {
//            $newData[$key]['value'] = $datum['id'];
//            $newData[$key]['label'] = $datum['name'];
            if ($datum['pid'] == $parent_id) {
                //根节点直接把地址放到新数组中
                $tree[] = &$newData[$key];
            } else {
                //不是根节点的将自己的地址放到父级的child节点
                $newData[$datum['pid']]['children'][] = &$newData[$key];
                //$newData[$datum['parent_id']]['son'][] = &$newData[$key];
            }
        }
        return $tree;
    }

    private function batchGetGoodsAttr($param){
//        $user = (new CatchAuth())->user();
//        $this->user = $user;
//        $this->user  = (new \catchAdmin\permissions\model\Users())->find(1);

        $goods_attr = [];
        //分割成20个
        $goods_spu_ids_chunk =  array_chunk(array_column($param['goods_data'],'goods_spu'),20);

        foreach ($goods_spu_ids_chunk as $value){
            $goods_attr =  array_merge($goods_attr, (new Goods)->goodsSpecPriceBatch([
                'goods_spu'=> implode(',',$value)
            ])['data']);
        }

        //属性
        $attr_key = array_column($goods_attr,'goods_spu');
        $param['goods_attr'] = array_combine($attr_key,$goods_attr);

        return $param;
    }

    //远程数据和本地数据库对比，返回需要处理的数据
    private function remoteLocalCheck($param,$return_param = 'remote'){
//        $user = (new CatchAuth())->user();
//        $this->user = $user;
//        $this->user  = (new \catchAdmin\permissions\model\Users())->find(1);

        //远程goods_spu
        $goods_spu_ids = array_column($param['goods_data'],'goods_spu');

        //本地goods_spu
        $goodsModel = new externalGoodsModel;
        $existResult = $goodsModel
            ->where('supplier_id',1)// 代理商 =》 候鸟
            ->where('goods_spu','in',$goods_spu_ids)->column('goods_spu');

        foreach ($param['goods_data'] as $key => &$value){
            if($value['is_sale'] == 0){//下架的商品
                unset($param['goods_data'][$key]);
                continue;
            }

            if(in_array($value['goods_spu'],$existResult)){
                $value['is_exist'] = true;
            }else{
                $value['is_exist'] =  false;
                continue;
            }

            if($return_param == 'remote'){//只返回远程没有的
                unset($param['goods_data'][$key]);
            }
        }

        //规格
        $param = $this->batchGetGoodsAttr($param);
        foreach ($param['goods_data'] as &$value){
            if(array_key_exists($value['goods_spu'],$param['goods_attr'])){
                $value['goods_attr'] = $param['goods_attr'][$value['goods_spu']]['sku_list'];
            }else{
                $value['goods_attr']  = [];
            }
        }
//       $attr_res = $this->batchGetGoodsAttr($param);
//        dd($attr_res['goods_attr']);


        return $param;
    }


    //处理批量添加商品
    private function batchDealGoods($param){
//        $user = (new CatchAuth())->user();
//        $this->user = $user;
//        $this->user  = (new \catchAdmin\permissions\model\Users())->find(1);

        $goods_arr = [];
        //要添加的商品表数据
        foreach ($param['goods_data'] as $key => &$value){
            //$data = $value;
            $value['ext_id'] = (string) $value['goods_spu'];
            $value['supplier_id'] = 1;
            $value['creator_id'] = $this->user['id'];

            $value['spec'] = 2;//候鸟默认都是多规格。

            //图片 描述
            $value['goods_img'] = $value['goods_img']['img'];
            $value['goods_slideshow_img'] = json_encode(array_column($value['goods_slideshow_img'],'slideshow_img'));
            $value['category_name'] = json_encode($value['category_name']);
            //$goods_arr[] = $data;
            //其他类型字段
            $value['sync_brand_id'] = $value['brand_id'];
            $value['sync_brand_name'] = $value['brand_name'];
            $value['sync_category_id'] = $value['category_id'];
            $value['sync_category_id_path'] = $value['category_id_path'];
            $value['sync_category_name'] = $value['category_name'];
            $value['description'] = $value['goods_desc'];

            if($model =  (new externalGoodsModel())
                ->where([
                    'supplier_id'=>1,
                    'goods_spu'=>$value['goods_spu']
                ])
                ->find()){
                $model->save($value);
            }else{
                unset($value['id']);
                $model =  new externalGoodsModel;
                $model->save($value);
            }

            //返回goods_id
            $value['id'] = $model->id;
        }

        return $param;
    }

    //处理批量添加商品属性
    private function batchDealGoodsAttr($param)
    {
//        $user = (new CatchAuth())->user();
//        $this->user = $user;
//        $this->user  = (new \catchAdmin\permissions\model\Users())->find(1);

        $_key = array_column($param['goods_data'],'goods_spu');
        $_goods = array_combine($_key,$param['goods_data']);

        $goods_attr = [];
        foreach ($param['goods_attr'] as $key => &$value) {

            if(empty($value['attribute_list'])){
                continue;
            }

            foreach ($value['attribute_list'] as $k1 => &$v1){
                if(empty($v1['items'])){//处理有属性，没有规格的问题
                    continue;
                }
                foreach ($v1['items'] as $k2 => &$v2){
                    $goods_attr[] = [
                        'name'=>$v1['name'],
                        'attribute_id'=>$v2['attribute_id'],
                        'attribute_name'=>$v2['attribute_name'],
                        'goods_id'=> $_goods[$value['goods_spu']]['id'],
                        'goods_spu'=>$value['goods_spu'],
                        'supplier_id'=>1,//候鸟
                        'creator_id'=>$this->user['id'],
                    ];
                }

            }
        }


        Db::startTrans();
        try {
            //删除属性
            Db::table('db_syst_sync_goods_attribute')
                ->where('supplier_id',1)
                ->where('attribute_id','in',array_column($goods_attr,'attribute_id'))
                ->delete();

            //添加属性
            $goodsAttribute = (new externalGoodsAttribute());
            $goodsAttribute->saveAll($goods_attr);

            Db::commit();
            return $param;
        } catch (\Exception $exception) {
            Db::rollback();
            throw new Exception('属性添加失败');
        }
    }

    //处理批量添加商品属性
    private function batchDealGoodsRule($param,$supplier_id = 1)
    {
//        $user = (new CatchAuth())->user();
//        $this->user = $user;
//        $this->user  = (new \catchAdmin\permissions\model\Users())->find(1);

        $_key = array_column($param['goods_data'],'goods_spu');
        $_goods = array_combine($_key,$param['goods_data']);

        $goods_rule = [];
        foreach ($param['goods_attr'] as $key => &$value) {

            if(empty($value['sku_list'])){
                continue;
            }
            $goodsAllStock = 0;
            $goodsPriceMap = [];
            $goodsCostPriceMap = [];
            foreach ($value['sku_list'] as $k1 => &$v1){
                $goodsAllStock += $v1['sku_stock'];
                $goodsPriceMap[] =  round($v1['sku_price'] * $this->price_fl);
                $goodsCostPriceMap[] =  $v1['sku_price'];

                $goods_rule[] = [
                    'ext_id'=>$v1['sku_id'],
                    'goods_sku'=>$v1['sku_id'],
                    'goods_id'=> $_goods[$value['goods_spu']]['id'],
                    'goods_spu'=>$value['goods_spu'],
                    'spec_sku' => $v1['spec_sku'],
                    'sku_name' => $v1['sku_name'],
                    'sku_attribute_id' => json_encode($v1['sku_attribute_id']),
                    'sku_attribute_name' => json_encode($v1['sku_attribute_name']),
                    'sku_price' =>  round($v1['sku_price'] * $this->price_fl),
                    'cost_price' => $v1['sku_price'],//成本价
                    //活动价
                    'activity_price' => isset($v1['activity_price']) ?? 0,
                    'line_price' => isset($v1['line_price']) ?? 0,
                    'market_price' => isset($v1['market_price']) ?? 0,

                    'sku_weight' => $v1['sku_weight'],
                    'sku_quantity' => $v1['sku_quantity'],
                    'sku_stock' => $v1['sku_stock'],
                    'supplier_id'=>$supplier_id,//候鸟
                    'creator_id'=>$this->user['id'],
                ];
            }
            //修改库存 和 价格
            $goodsParam = [
                'stock'=>$goodsAllStock,
                'price'=>min($goodsPriceMap),
                'cost_price'=>min($goodsCostPriceMap)
            ];
            $goodsModel = new externalGoodsModel;
            $goodsModel->updateBy($_goods[$value['goods_spu']]['id'],$goodsParam);
        }

        Db::startTrans();
        try {
            //删除规格
            Db::table('db_syst_sync_goods_rule')
                ->where('supplier_id',$supplier_id)
                ->where('goods_id','in',array_column($goods_rule,'goods_id'))
                ->where('goods_sku','in',array_column($goods_rule,'sku_id'))
                ->delete();

            //添加属性
            $goodsRule = new externalGoodsRuleModel;
            $goodsRule->saveAll($goods_rule);



            Db::commit();
            return $param;
        } catch (\Exception $exception) {
            Db::rollback();
            throw new Exception('sku添加失败');
        }
    }


    //通知商品新增
    public function notifyGoodsAdd($param){
        $model = new externalGoodsModel();
        $goods_id =  $model->where('goods_spu',$param['goods_spu'])->value('id');

        if($goods_id > 0){//如果商品存在，那就给拦截了
//            return false;
            return '商品已存在，无法新增';
        }

        //商品详情
        $goods_res = (new Goods())->detail(['goods_spu'=>$param['goods_spu'],'old_goods_spu'=>$param['old_goods_spu']])['data'];
        $attr_res = (new Goods)->goodsSpecPrice(['goods_spu'=>$param['goods_spu'],'old_goods_spu'=>$param['old_goods_spu']])['data'];

        if(1 == $goods_res['is_transition']){//自付商品不需要
//            throw new Exception('过滤、自付商品');
            return '过滤、自付商品';
        }

        Db::startTrans();
        try {
            //添加商品
            $goods =  $this->addGoods($goods_res);
            //添加属性
            $this->addAttr($attr_res,$goods->id,$goods->goods_spu);
            //添加规格
            $this->addRule($attr_res,$goods->id,$goods->goods_spu);

            //更换替换到本地
            //$this->replacePic($goods->id);

            Db::commit();
            return true;
        } catch (\Exception $exception) {
            Db::rollback();
            return $exception->getMessage();
        }
    }

    //商品订阅
    public function goodsSubscribe($param,$is_subscribe = 1){
        if(!is_array($param)){
            $param = [$param];
        }

        $goods_spu = implode(',',$param);

        $goodsApi = new Goods;

        $data = $goodsApi->goodsSubscribe(['goods_spu'=>$goods_spu,'is_subscribe'=>$is_subscribe]);

        return $data;
    }

    //通知商品修改
    public function notifyGoodsUpdate($param)
    {
        $model = new externalGoodsModel();
        $goods_result =  $model->where('goods_spu',$param['goods_spu'])->field('id,is_sale,category_id,trade_type_id,goods_spu')->find();
        if(!$goods_result){
            return '数据库商品并不存在';
        }
        $goods_result = $goods_result->toArray();

        $goods_id = $goods_result['id'];
        $is_sale = $goods_result['is_sale'];
//        $goods_id =  $model->where('goods_spu',$param['goods_spu'])->value('id');

        //判断商品分类是否是禁用分类&贸易类型ID=3
        $categoryService = new CategoryService();
        $disabledCategories = $categoryService->getDisabledCategories();
        if (in_array($goods_result['category_id'], $disabledCategories) && $goods_result['trade_type_id'] == 3) {
            $delete_res = $this->deleteGoods($goods_id);
            return $delete_res;
        }

        //商品详情
        $goods_res = (new Goods())->detail(['goods_spu'=>$param['goods_spu'],'old_goods_spu'=>$param['old_goods_spu']])['data'];
        //库存属性价格
        $attr_res = (new Goods)->goodsSpecPrice(['goods_spu'=>$param['goods_spu'],'old_goods_spu'=>$param['old_goods_spu']])['data'];

        Db::startTrans();
        try {
            //修改商品
            $goods =  $this->updateGoods($goods_res);

            //更换替换到本地
            //$this->replacePic($goods->id);

            Db::commit();
            return true;
        } catch (\Exception $exception) {
            Db::rollback();
            return $exception->getMessage();
        }
    }

    //通知商品上架
    public function notifyGoodsShelve($param){
        //03.14修改
//        //商品详情
//        $goods_res = (new Goods())->detail(['goods_spu'=>$param['goods_spu'],'old_goods_spu'=>$param['old_goods_spu']])['data'];
//        $attr_res = (new Goods)->goodsSpecPrice(['goods_spu'=>$param['goods_spu'],'old_goods_spu'=>$param['old_goods_spu']])['data'];

        try {
            $goods_res = (new Goods())->detail(['goods_spu'=>$param['goods_spu'],'old_goods_spu'=>$param['old_goods_spu']])['data'];
            $attr_res = (new Goods)->goodsSpecPrice(['goods_spu'=>$param['goods_spu'],'old_goods_spu'=>$param['old_goods_spu']])['data'];
        }catch (\Exception $exception){
            //捕获到接口异常，可能没有数据。暂时下架处理
            $this->notifyGoodsUnShelveBySPU($param);
            return $exception->getMessage();
        }

        Db::startTrans();
        try {
            //修改商品
            $goods =  $this->updateGoods($goods_res);
            //修改属性
            $this->updateAttr($attr_res,$goods->id,$goods->goods_spu);
            //修改规格
            $this->updateRule($attr_res,$goods->id,$goods->goods_spu);

            $list = $this->tenantList;
            //给所有供应商更新
            foreach ($list as $value){
                $this->delAndInsGoods($goods->id,$param['goods_spu'],$value['tenant_id']);
            }

            Db::commit();
            return true;
        } catch (\Exception $exception) {
            Db::rollback();
            return $exception->getMessage();
        }
    }

    //商品下架
    public function notifyGoodsUnShelveBySPU($param){
        $spu_id = $param['goods_spu'];
        $model = (new externalGoodsModel)->where('goods_spu',$spu_id)->find();
        $model->is_sale = 0;//下架
        $model->save();

        $tenantGoodsModel = new tenantGoodsModel();
        $tenantGoodsModel->where('goods_spu',$spu_id)->save(['is_sale'=>0]);

        return true;
    }

    public function notifyGoodsPrice($param){
        $model = new externalGoodsModel();
        $goods_result =  $model->where('goods_spu',$param['goods_spu'])->field('id,is_sale,category_id,trade_type_id,goods_spu')->find();
        if(!$goods_result){
            return '数据库商品并不存在';
        }
        $goods_result = $goods_result->toArray();

        $goods_id = $goods_result['id'];
        $is_sale = $goods_result['is_sale'];
//        $goods_id =  $model->where('goods_spu',$param['goods_spu'])->value('id');

        //判断商品分类是否是禁用分类&贸易类型ID=3
        $categoryService = new CategoryService();
        $disabledCategories = $categoryService->getDisabledCategories();
        if (in_array($goods_result['category_id'], $disabledCategories) && $goods_result['trade_type_id'] == 3) {
            $delete_res = $this->deleteGoods($goods_id);
            return $delete_res;
        }

        try {
            $attr_res = (new Goods)->goodsSpecPrice(['goods_spu'=>$param['goods_spu'],'old_goods_spu'=>$param['old_goods_spu']])['data'];
            $goods_res = (new Goods())->detail(['goods_spu'=>$param['goods_spu'],'old_goods_spu'=>$param['old_goods_spu']])['data'];
        }catch (\Exception $exception){
            //捕获到接口异常，可能没有数据。暂时下架处理
            $this->notifyGoodsUnShelveBySPU($param);
            return $exception->getMessage();
        }

        Db::startTrans();
        try {
            //判断当前商品是否是下架
            if($goods_res['is_sale']  !=  $is_sale){//当前商品状态不一致
                if(1 == $goods_res['is_sale']){
                    $this->notifyGoodsShelve($param);
                }else{
                    $this->notifyGoodsUnShelveBySPU($param);
                }
            }else{
                //修改商品
                $goods =  $this->updateGoods($goods_res);
                //修改属性
                $this->updateAttr($attr_res,$goods_id,$param['goods_spu']);
                //修改规格
                $this->updateRule($attr_res,$goods_id,$param['goods_spu']);

                $list = $this->tenantList;

                //给所有供应商更新
                foreach ($list as $value){
                    $this->delAndInsGoods($goods_id,$param['goods_spu'],$value['tenant_id']);
                }
            }

            Db::commit();
            return true;
        } catch (\Exception $exception) {
            Db::rollback();
            return $exception->getMessage();
//            return false;
        }
    }

    //海淘汇的测试方法
    public function notifyGoodsPrice2($param){
        try {
            $list = (new \hth\api\v1\Goods())->detail(["sys_spu"=>$param['goods_spu']])['data'];
        }catch (\Exception $exception){
            //捕获到接口异常，可能没有数据。暂时下架处理
            $this->notifyGoodsUnShelveBySPU($param);
            return $exception->getMessage();
        }

        $g['id'] = (new externalGoodsModel)->where('goods_spu',$param['goods_spu'])->value('id');

        $temp =  Db::table('temp_table_10050')->field('brand_name,origin_name as area,description as content')
            ->where('goods_spu', $param['goods_spu'])->find();
        if(empty($temp)) {
            $temp = [];
        }
        $list = array_merge($list,$temp);

        Db::startTrans();
        try {
            $remoteGoodsService = new RemoteGoodsService;
            $resss = $remoteGoodsService->hthGoodsUpdate($g['id'],$param['goods_spu'],$list);

            if(1 != $resss['status']){
                throw new Exception('海淘汇更新失败');
            }

            $list = $this->tenantList;

            //给所有供应商更新
            foreach ($list as $value){
                $this->delAndInsGoods($g['id'],$param['goods_spu'],$value['tenant_id']);
            }

            Db::commit();
            return true;
        } catch (\Exception $exception) {
            Db::rollback();
            return false;
        }
    }

    public function notifyGoodsStock($param){
        $model = new externalGoodsModel();
        $goods_result =  $model->where('goods_spu',$param['goods_spu'])->field('id,is_sale,category_id,trade_type_id,goods_spu')->find();
        if(!$goods_result){
            return '数据库商品并不存在';
        }
        $goods_result = $goods_result->toArray();

        $goods_id = $goods_result['id'];
        $is_sale = $goods_result['is_sale'];
//        $goods_id =  $model->where('goods_spu',$param['goods_spu'])->value('id');

        //判断商品分类是否是禁用分类&贸易类型ID=3
        $categoryService = new CategoryService();
        $disabledCategories = $categoryService->getDisabledCategories();
        if (in_array($goods_result['category_id'], $disabledCategories) && $goods_result['trade_type_id'] == 3) {
            $delete_res = $this->deleteGoods($goods_id);
            return $delete_res;
        }

        try {
            $attr_res = (new Goods)->goodsSpecPrice(['goods_spu'=>$param['goods_spu'],'old_goods_spu'=>$param['old_goods_spu']])['data'];
            $goods_res = (new Goods())->detail(['goods_spu'=>$param['goods_spu'],'old_goods_spu'=>$param['old_goods_spu']])['data'];
        }catch (\Exception $exception){
            //捕获到接口异常，可能没有数据。暂时下架处理
            $this->notifyGoodsUnShelveBySPU($param);
            return $exception->getMessage();
        }

        Db::startTrans();
        try {
            //判断当前商品是否是下架
            if($goods_res['is_sale']  !=  $is_sale){//当前商品状态不一致
                if(1 == $goods_res['is_sale']){
                    $this->notifyGoodsShelve($param);
                }else{
                    $this->notifyGoodsUnShelveBySPU($param);
                }
            }else{
                //修改商品
                $goods =  $this->updateGoods($goods_res);
                //修改属性
                $this->updateAttr($attr_res,$goods_id,$param['goods_spu']);
                //修改规格
                $this->updateRule($attr_res,$goods_id,$param['goods_spu']);

                $list = $this->tenantList;

                //给所有供应商更新
                foreach ($list as $value){
                    $this->delAndInsGoods($goods_id,$param['goods_spu'],$value['tenant_id']);
                }
            }

            Db::commit();
            return true;
        } catch (\Exception $exception) {
            Db::rollback();
            return $exception->getMessage();
//            return false;
        }
    }

    private function deleteGoodsByGoodsID($goods_id){
        $res = Db::table('db_syst_sync_goods')->where('id',$goods_id)->delete();

        if(!$res){
            throw new Exception('商品删除失败');
        }

        return true;
    }

    private function addGoods($data){
        $data['ext_id'] = (string) $data['goods_spu'];
        $data['supplier_id'] = 1;

        $data['spec'] = 2;//候鸟默认都是多规格。

        //图片 描述
        $data['goods_img'] = $data['goods_img']['img'];
        $data['goods_slideshow_img'] = json_encode(array_column($data['goods_slideshow_img'],'slideshow_img'));
        $data['category_name'] = json_encode($data['category_name']);
        //其他类型字段
        $data['sync_brand_id'] = $data['brand_id'];
        $data['sync_brand_name'] = $data['brand_name'];
        $data['sync_category_id'] = $data['category_id'];
        $data['sync_category_id_path'] = $data['category_id_path'];
        $data['sync_category_name'] = $data['category_name'];
        $data['description'] = $data['goods_desc'];

        //0508修改，重新绑定新的分类
        $data['category_id'] = (int) (new Category)->where(['hn_cate_id'=>$data['category_id']])->value('id');

        // 检查分类是否被禁用
        $categoryService = new CategoryService();
        $disabledCategories = $categoryService->getDisabledCategories();
        if (in_array($data['category_id'], $disabledCategories) && $data['trade_type_id'] == 3) {
            throw new Exception('商品分类，禁用');
        }

        $model = new externalGoodsModel();
        $res = $model->save($data);

        if(!$res){
            throw new Exception('商品添加失败');
        }

        return $model;
    }

    private function updateGoods($data){
        $model = new externalGoodsModel();
        $goods =  $model->where('goods_spu',$data['goods_spu'])->find();

        if(empty($goods)){
            throw new Exception('商品不存在');
        }

        $data['ext_id'] = (string) $data['goods_spu'];
        $data['supplier_id'] = 1;

        $data['spec'] = 2;//候鸟默认都是多规格。

        //图片 描述
        $data['goods_img'] = $data['goods_img']['img'];
        $data['goods_slideshow_img'] = json_encode(array_column($data['goods_slideshow_img'],'slideshow_img'));
        $data['category_name'] = json_encode($data['category_name']);

        //其他类型字段
        $data['sync_brand_id'] = $data['brand_id'];
        $data['sync_brand_name'] = $data['brand_name'];
        $data['sync_category_id'] = $data['category_id'];
        $data['sync_category_id_path'] = $data['category_id_path'];
        $data['sync_category_name'] = $data['category_name'];
        $data['description'] = $data['goods_desc'];

        //0508修改，重新绑定新的分类
        $data['category_id'] = (int) (new Category)->where(['hn_cate_id'=>$data['category_id']])->value('id');

        unset($data['id']);

        $res = $goods->save($data);

        if(!$res){
            throw new Exception('商品添加失败');
        }

        return $goods;
    }

    private function addAttr($data,$goods_id,$good_spu){

        if(empty($data['attribute_list'])){
            return true;
        }

        $goods_attr = [];

        foreach ($data['attribute_list'] as $k1 => &$v1){
            if(empty($v1['items'])){//处理有属性，没有规格的问题
                continue;
            }
            foreach ($v1['items'] as $k2 => &$v2){
                $goods_attr[] = [
                    'name'=>$v1['name'],
                    'attribute_id'=>$v2['attribute_id'],
                    'attribute_name'=>$v2['attribute_name'],
                    'goods_id'=> $goods_id,
                    'goods_spu'=>$good_spu,
                    'supplier_id'=>1,//候鸟
                ];
            }
        }

        //添加属性
        $goodsAttribute = (new externalGoodsAttribute());
        $res =  $goodsAttribute->saveAll($goods_attr);

        if(!$res){
            throw new Exception('属性添加失败');
        }

        return $res;
    }

    private function updateAttr($data,$goods_id,$good_spu){
        if(empty($data['attribute_list'])){
            return true;
        }

        $goods_attr = [];

        foreach ($data['attribute_list'] as $k1 => &$v1){
            if(empty($v1['items'])){//处理有属性，没有规格的问题
                continue;
            }
            foreach ($v1['items'] as $k2 => &$v2){
                $goods_attr[] = [
                    'name'=>$v1['name'],
                    'attribute_id'=>$v2['attribute_id'],
                    'attribute_name'=>$v2['attribute_name'],
                    'goods_id'=> $goods_id,
                    'goods_spu'=>$good_spu,
                    'supplier_id'=>1,//候鸟
                ];
            }
        }

        //属性的新增、删除、修改
        $goodsAttributeModel = (new externalGoodsAttribute());

        //所有已经存在的属性
        $attrExistResult = $goodsAttributeModel->lock(true)->where('goods_id',$goods_id)->select()->toArray();
        $attrExistAttrID = array_column($attrExistResult,'attribute_id');
        $attrExistAttrPKID = array_column($attrExistResult,'id');

        $attrExistNewArr = array_combine($attrExistAttrID,$attrExistResult);

        $insert = [];
        $delete = $attrExistNewArr;

        Db::startTrans();
        try {
            foreach ($goods_attr as $value){
                if (!isset($attrExistNewArr[$value['attribute_id']])) {
                    $insert[] = $value;
                } else {
                    // 存在的，更新
                    unset($value['id']);
                    $goodsAttributeModel->updateBy($attrExistNewArr[$value['attribute_id']]['id'], $value);

                    unset($delete[$value['attribute_id']]);
                    //从其中踢出
                    unset($attrExistAttrPKID[array_search($attrExistNewArr[$value['attribute_id']]['id'],$attrExistAttrPKID)]);
                }
            }

            // 本次新增的插入
            $goodsAttributeModel->saveAll($insert);
            // 已经删除的，则删掉
            if(!empty($delete)){
                $goodsAttributeModel->deleteBy(array_column($delete,'id'));
            }
            //已存在，相同的

//            dd(array_values($attrExistAttrPKID));
            if(!empty($attrExistAttrPKID)){
                $goodsAttributeModel->deleteBy(array_values($attrExistAttrPKID));
            }

            Db::commit();
            return true;
        } catch (\Exception $exception) {
            Db::rollback();
            throw new Exception($exception->getMessage());
        }
    }

    private function addRule($data,$goods_id,$good_spu){
        if(empty($data['sku_list'])){
            return false;
        }
        $goods_rule = [];

        $goodsAllStock = 0;
        $goodsPriceMap = [];
        foreach ($data['sku_list'] as $k1 => &$v1){
            $goodsAllStock += $v1['sku_stock'];
            $goodsPriceMap[] =  round($v1['sku_price'] * $this->price_fl);
            $goodsCostPriceMap[] =  $v1['sku_price'];

            $goods_rule[] = [
                'ext_id'=>$v1['sku_id'],
                'goods_sku'=>$v1['sku_id'],
                'goods_id'=> $goods_id,
                'goods_spu'=>$good_spu,
                'spec_sku' => $v1['spec_sku'],
                'sku_name' => $v1['sku_name'],
                'sku_attribute_id' => json_encode($v1['sku_attribute_id']),
                'sku_attribute_name' => json_encode($v1['sku_attribute_name']),
                'sku_price' =>  round($v1['sku_price'] * $this->price_fl),
                'cost_price' => $v1['sku_price'],//成本价
                //活动价
                'activity_price' => isset($v1['activity_price']) ?? 0,
                'line_price' => isset($v1['line_price']) ?? 0,
                'market_price' => isset($v1['market_price']) ?? 0,

                'sku_weight' => $v1['sku_weight'],
                'sku_quantity' => $v1['sku_quantity'],
                'sku_stock' => $v1['sku_stock'],
                'supplier_id'=>1,//候鸟
            ];
        }

        //添加属性
        $goodsRule = new externalGoodsRuleModel;
        $res  = $goodsRule->saveAll($goods_rule);

        //修改库存 和 价格
        $goodsParam = [
            'stock'=>$goodsAllStock,
            'price'=>min($goodsPriceMap),
            'cost_price'=>min($goodsCostPriceMap)
        ];
        $goodsModel = new externalGoodsModel;
        $res1 =  $goodsModel->updateBy($goods_id,$goodsParam);

        if($res && $res1){
            return $res;
        }else{
            throw new Exception('规格添加失败');
        }

    }

    private function updateRule($data,$goods_id,$good_spu){
        if(empty($data['sku_list'])){
            return false;
        }
        $goods_rule = [];

        $goodsAllStock = 0;
        $goodsPriceMap = [];
        $goodsCostPriceMap = [];
        foreach ($data['sku_list'] as $k1 => &$v1){
            $goodsAllStock += $v1['sku_stock'];
            $goodsPriceMap[] =  round($v1['sku_price'] * $this->price_fl);
            $goodsCostPriceMap[] =  $v1['sku_price'];

            $goods_rule[] = [
                'ext_id'=>$v1['sku_id'],
                'goods_sku'=>$v1['sku_id'],
                'goods_id'=> $goods_id,
                'goods_spu'=>$good_spu,
                'spec_sku' => $v1['spec_sku'],
                'sku_name' => $v1['sku_name'],
                'sku_attribute_id' => json_encode($v1['sku_attribute_id']),
                'sku_attribute_name' => json_encode($v1['sku_attribute_name']),
                'sku_price' =>  round($v1['sku_price'] * $this->price_fl),
                'cost_price' => $v1['sku_price'],
                //活动价
                'activity_price' => isset($v1['activity_price']) ?? 0,
                'line_price' => isset($v1['line_price']) ?? 0,
                'market_price' => isset($v1['market_price']) ?? 0,

                'sku_weight' => $v1['sku_weight'],
                'sku_quantity' => $v1['sku_quantity'],
                'sku_stock' => $v1['sku_stock'],
                'supplier_id'=>1,//候鸟
            ];
        }

        //规格的新增、删除、修改
        $goodsRuleModel = (new externalGoodsRuleModel());

        //所有已经存在的属性
        $ruleExistResult = $goodsRuleModel->lock(true)->where('goods_id',$goods_id)->select()->toArray();
        $ruleExistSkuID = array_column($ruleExistResult,'goods_sku');
        $ruleExistRulePKID = array_column($ruleExistResult,'id');

        $ruleExistNewArr = array_combine($ruleExistSkuID,$ruleExistResult);

        $insert = [];
        $delete = $ruleExistNewArr;

        Db::startTrans();
        try {
            foreach ($goods_rule as $value){
                if (!isset($ruleExistNewArr[$value['goods_sku']])) {
                    $insert[] = $value;
                } else {
                    // 存在的，更新
                    unset($value['id']);
                    $goodsRuleModel->updateBy($ruleExistNewArr[$value['goods_sku']]['id'], $value);

                    unset($delete[$value['goods_sku']]);
                    //从其中踢出
                    unset($ruleExistRulePKID[array_search($ruleExistNewArr[$value['goods_sku']]['id'],$ruleExistRulePKID)]);
                }
            }

            // 本次新增的插入
            $res1_save = $goodsRuleModel->saveAll($insert);
            // 已经删除的，则删掉
            $res1_del = true;
            if(!empty($delete)){
                $res1_del =  $goodsRuleModel->deleteBy(array_column($delete,'id'));
            }

            //已存在，相同的
            if(!empty($ruleExistRulePKID)){
                $goodsRuleModel->deleteBy(array_values($ruleExistRulePKID));
            }

            //修改库存 和 价格
            $goodsParam = [
                'stock'=>$goodsAllStock,
                'price'=>min($goodsPriceMap),
                'cost_price'=>min($goodsCostPriceMap)
            ];
            $goodsModel = new externalGoodsModel;
            $res1 =  $goodsModel->updateBy($goods_id,$goodsParam);

            if($res1 && $res1_del && $res1_save){
                Db::commit();
            }else{
                Db::rollback();
                throw new Exception('商品规格修改失败');
            }

            return true;
        } catch (\Exception $exception) {
            Db::rollback();
            throw new Exception($exception->getMessage());
        }
    }

    //供应商或管理员后台添加商品
    public function createGoods($param,$mode){
        //检验参数

        //添加商品
        Db::startTrans();
        try {
            $this->goodsTemplate($param,$mode);

            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();
            return CatchResponse::fail('添加失败' . $exception->getMessage());
        }

        return CatchResponse::success([],'success');
    }

    //供应商或管理员后台修改商品
    public function editGoods($param,$mode){
        //检验参数

        Db::startTrans();
        try {
            $this->goodsTemplate($param,$mode);

            $goods_info = (new externalGoodsModel())->findBy($param['id']);

            //更新供应商商品
            $this->updateGoodsBySupplier($param['id'],$goods_info['goods_spu']);

            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();
            return CatchResponse::fail('修改失败' . $exception->getMessage());
        }
        return CatchResponse::success([],'success');
    }

    //商品参数
    public function checkParam($param,$mode){
        if(1 == $param['spec']){//单规格
            if (empty($param['price']) || $param['price'] < 0) {
                throw new Exception("请输入大于等于0的售价");
            }

            if ($param['stock'] == '' || $param['stock'] < 0) {
                throw new Exception("请输入大于等于0的库存");
            }
        }elseif(2 == $param['spec']){//多规格
            if(empty($param['goods_attr']) || empty($param['goods_rule'])){
                throw new Exception("规格没有传值");
            }
        }


    }

    //处理商品业务
    public function goodsTemplate($param,$mode){
        //校验参数
        $this->checkParam($param,$mode);

        //处理商品基础数据
        $goods =  $this->dealBase($param,$mode);

        //处理商品属性
        $param['goods_spu'] = $goods->goods_spu;
        $param['id'] = $goods->id;

        if(2 == $param['spec']){
            $this->dealAttr($param,$mode);

            //处理商品规格
            $this->dealRule($param,$mode);
        }
        //处理商品其他东西
    }

    private function dealBase($param,$mode){
        $goodsModel = new externalGoodsModel;

        $goods_img = $param['goods_img'];
        $param['goods_img'] = array_shift($goods_img);//主图
        $param['goods_slideshow_img'] = json_encode($goods_img);//轮播图

        //分类ID
//        $param['category_id'] = (new Category)->where('id',$param['category_id'])->value('cate_id');

        if($mode == 'edit'){
            unset($param['goods_spu']);
            unset($param['supplier_id']);
            $goodsModel = $goodsModel->where('id',$param['id'])->find();
            $goodsModel->save($param);
        }else{
            if(1== $this->user['type']){//管理员的话
                $supplier_id = 0;
            }else{
                $supplier_id = $this->user['tenant_id'];
            }

            $param['goods_spu'] = 'G' . date("YmdHis") . mt_rand(1000,9999);
            $param['create_mode'] = 1;//后台创建
            $param['supplier_id'] = $supplier_id;
            $goodsModel->storeBy($param);
        }

        //判断传参数是否有crossBorderParams
        if(isset($param['crossBorderParams']) && !empty($param['crossBorderParams'])){
            $goods_id = $goodsModel->id;
            $this->dealCrossBorderParams($goods_id,$param['crossBorderParams']);
        }

        return $goodsModel;
    }

    private function dealCrossBorderParams($goods_id,$crossBorderParams){
        $customerModel = new GoodsCustomerModel;
        //存在就更新，否则就新增
        if($res = $customerModel->where('goods_id',$goods_id)->find()){
            $customerModel->updateBy($res['id'],$crossBorderParams);
        }else{
            $crossBorderParams['goods_id'] = $goods_id;
            $customerModel->storeBy($crossBorderParams);
        }

        return true;
    }

    private function dealAttr($param,$mode){
        $goods_attr = json_decode(json_encode($param['goods_attr']),true);

        //属性的新增、删除、修改
        $goodsAttributeModel = (new externalGoodsAttribute());

        //获取数据库中已存在的所有属性
        $existAttrs = $goodsAttributeModel->where('goods_id',$param['id'])->select()->toArray();
        
        //构造属性的唯一标识(name:attribute_name)
        $getAttrKey = function($attr) {
            return $attr['name'] . ':' . $attr['attribute_name'];
        };
        
        //获取现有属性的唯一标识
        $existAttrKeys = array_map($getAttrKey, $existAttrs);
        
        //获取新属性的唯一标识
        $newAttrKeys = array_map($getAttrKey, $goods_attr);
        
        //计算需要删除的属性
        $toDelete = array_diff($existAttrKeys, $newAttrKeys);
        
        //计算需要新增的属性
        $toInsert = array_diff($newAttrKeys, $existAttrKeys);
        
        //计算需要更新的属性
        $toUpdate = array_intersect($newAttrKeys, $existAttrKeys);

        //构建existAttrs的查找索引
        $existAttrsMap = [];
        foreach ($existAttrs as $attr) {
            $key = $getAttrKey($attr);
            $existAttrsMap[$key] = $attr;
        }
        
        $insert = [];

        if(1== $this->user['type']){//管理员的话
            $supplier_id = 0;
        }else{
            $supplier_id = $this->user['tenant_id'];
        }

        Db::startTrans();
        try {
            foreach ($goods_attr as &$value) {
                $attrKey = $getAttrKey($value);

                //之前的有问题，修改下
                $value['supplier_id'] = $supplier_id; //候鸟

                if (in_array($attrKey, $toInsert)) {
                    // 新增的属性
                    $value['attribute_id'] = date("YmdHis") . mt_rand(1000, 9999);
                    $value['goods_id'] = $param['id'];
                    $value['goods_spu'] = $param['goods_spu'];
                    $insert[] = $value;
                } elseif (in_array($attrKey, $toUpdate)) {
                    // 更新的属性
                    $existAttr = $existAttrsMap[$attrKey];
                    // 保持原有的attribute_id
                    $value['attribute_id'] = $existAttr['attribute_id'];
                    $goodsAttributeModel->updateBy($existAttr['id'], $value);
                }
            }

            // 批量新增
            if (!empty($insert)) {
                $goodsAttributeModel->saveAll($insert);
            }

            // 批量删除
            if (!empty($toDelete)) {
                $deleteIds = [];
                foreach ($toDelete as $key) {
                    $deleteIds[] = $existAttrsMap[$key]['id'];
                }
                $goodsAttributeModel->deleteBy($deleteIds);
            }

            Db::commit();
            return true;
        } catch (\Exception $exception) {
            Db::rollback();
            throw new Exception(json_encode($exception->getMessage()));
        }
    }

    private function dealRule($param,$mode){
        $goods_rule = json_decode(json_encode($param['goods_rule']),true);

        //规格的新增、删除、修改
        $goodsRuleModel = (new externalGoodsRuleModel());
        $goodsAttrModel = new externalGoodsAttribute();
        $goodsModel = new externalGoodsModel;

        //获取数据库中已存在的所有规格
        $existRules = $goodsRuleModel->where('goods_id', $param['id'])->select()->toArray();
        $existSkuNames = array_column($existRules, 'sku_name');
        
        //获取前端传来的所有规格名
        $newSkuNames = array_column($goods_rule, 'sku_name');
        
        //计算需要删除的规格(在数据库中存在但不在新数据中的)
        $toDelete = array_diff($existSkuNames, $newSkuNames);
        
        //计算需要新增的规格(在新数据中存在但不在数据库中的)
        $toInsert = array_diff($newSkuNames, $existSkuNames);
        
        //计算需要更新的规格(新旧数据中都存在的)
        $toUpdate = array_intersect($newSkuNames, $existSkuNames);

        //构建existRules的查找索引
        $existRulesMap = array_column($existRules, null, 'sku_name');
        
        $insert = [];
        $goodsStock = 0;
        $goodsPriceMap = [];
        $costPriceMap = [];

        if(1== $this->user['type']){//管理员的话
            $supplier_id = 0;
        }else{
            $supplier_id = $this->user['tenant_id'];
        }

        Db::startTrans();
        try {
            $random = mt_rand(1000, 9999);
            foreach ($goods_rule as &$value) {
                $goodsStock += $value['sku_stock'];
                $goodsPriceMap[] = $value['sku_price'];
                $costPriceMap[] = $value['cost_price'];
                
                ++$random;

                $value['supplier_id'] = $supplier_id;

                if (in_array($value['sku_name'], $toInsert)) {
                    // 新增的规格
                    $value['goods_sku'] = date("YmdHis") . $random;
                    $value['goods_spu'] = $param['goods_spu'];
                    $value['goods_id'] = $param['id'];

                    $new_sku_name = explode(';', $value['sku_name']);
                    $sku_name_arr = [];
                    
                    foreach ($new_sku_name as $v) {
                        $temp = explode(':', $v);
                        $sku_name_arr[] = $goodsAttrModel
                            ->field('attribute_id,attribute_name')
                            ->where([
                                'goods_id' => $param['id'],
                                'name' => $temp[0],
                                'attribute_name' => $temp[1]
                            ])
                            ->find();
                    }

                    $value['spec_sku'] = implode('_', array_column($sku_name_arr, 'attribute_id'));
                    $value['sku_attribute_id'] = json_encode(array_column($sku_name_arr, 'attribute_id'));
                    $value['sku_attribute_name'] = json_encode(array_column($sku_name_arr, 'attribute_name'));
                    
                    $insert[] = $value;
                } elseif (in_array($value['sku_name'], $toUpdate)) {
                    // 更新的规格
                    $existRule = $existRulesMap[$value['sku_name']];
                    $goodsRuleModel->updateBy($existRule['id'], $value);
                }
            }

            // 批量新增
            if (!empty($insert)) {
                $goodsRuleModel->saveAll($insert);
            }

            // 批量删除
            if (!empty($toDelete)) {
                $deleteIds = array_column(array_intersect_key($existRulesMap, array_flip($toDelete)), 'id');
                $goodsRuleModel->deleteBy($deleteIds);
            }

            // 更新商品总库存和最低显示价格
            if ($param['spec'] == 2) {
                $goodsParam = [
                    'stock' => $goodsStock,
                    'price' => min($goodsPriceMap),
                    'cost_price' => min($costPriceMap)
                ];
                $goodsModel->updateBy($param['id'], $goodsParam);
            }

            Db::commit();
            return true;
        } catch (\Exception $exception) {
            Db::rollback();
            throw new Exception(json_encode($exception->getMessage()));
        }
    }

    //给所有供应商更新
    public function updateGoodsBySupplier($goods_id,$goods_spu){
        $list = $this->tenantList;
        $goodsService = new GoodsService;

        //给所有供应商更新
        foreach ($list as $value){
            $goodsService->delAndInsGoods($goods_id,$goods_spu,$value['tenant_id']);
        }
    }

    //上传图片到服务器
    private function syncImage($src){
        $url = "https://img.qekj.net/upload_file.php?tid=cbecshop";

        //$src = "https://images.houniao.hk/upload/goods/20200807152685175_big.jpg";

        $file =  file_get_contents($src);

        $parts = parse_url($src);
        $filename = $parts['scheme'] . '://' . $parts['host'] . $parts['path'];

        $client = new \GuzzleHttp\Client();

        $response = $client->post($url, [
            'multipart' => [
                [
                    'name'     => 'file',
                    'contents' => $file,
                    'filename' => $filename
                ]
            ]
        ]);

        $result =  $response->getBody()->getContents();
        $result = json_decode($result,true);

        if(1 == $result['status']){
            return $result;
        }else{
            //dd($result);
            return false;
        }
    }

    public function replacePic($goods_id){

        $goodsModel = (new externalGoodsModel)->find($goods_id);
        $goodsResult = $goodsModel->toArray();

        //1-替换主图
        $_goods_img = $this->syncImage($goodsResult['goods_img'])['url'];

        //2-替换轮播图
        $goods_slideshow_img = json_decode($goodsResult['goods_slideshow_img'],true);
        $new_photo = [];
        foreach ($goods_slideshow_img as $k => $v){
            $upload = $this->syncImage($v);
            if(!$upload) continue;
            $new_photo[] = $upload['url'];
        }
        $_goods_slideshow_img = json_encode($new_photo);

        //3-替换详情图
        $description = $goodsResult['description'];
        $pattern = '/<img[^>]+src\s*=\s*["\']([^"\']+)["\'][^>]*>/i';
        preg_match_all($pattern, $description, $matches);

        $srcPaths = $matches[1];
        // 输出匹配到的src路径
        foreach ($srcPaths as $src) {
            //echo $src . "\n";
            $new_url = $this->syncImage($src)['http_url'];
            $description = str_replace($src,$new_url,$description);
        }

        //$saveData[] = $data;

        $goodsModel->description = $description;//详情图
        $goodsModel->goods_slideshow_img = $_goods_slideshow_img;//轮播图
        $goodsModel->goods_img = $_goods_img;//主图
        $goodsModel->is_upload_remote = 1;//主图

        $res =  $goodsModel->save();

        if(!$res){
            throw new Exception('图片保存失败');
        }
    }

    public function delAndInsGoods($syst_goods_id,$goods_spu,$tenant_id){

        $tenantGoodsModel = new tenantGoodsModel();
        $tenantGoodsAttrModel = new tenantGoodsAttrModel();
        $tenantGoodsRuleModel = new tenantGoodsRuleModel();

        //判断是否添加了东西
        $is_add = $tenantGoodsModel->where('tenant_id',$tenant_id)->where('goods_spu',$goods_spu)->find();
        if(!$is_add){
            return true;
        }

        Db::startTrans();
        try {

            //通过spu 删除
            $tenantGoodsModel::destroy(function($query) use ($tenant_id,$goods_spu){
                $query->where('tenant_id', $tenant_id)->where('goods_spu', $goods_spu);
            },true);

            $tenantGoodsAttrModel::destroy(function($query) use ($tenant_id,$goods_spu){
                $query->where('tenant_id', $tenant_id)->where('goods_spu', $goods_spu);
            },true);

            $tenantGoodsRuleModel::destroy(function($query) use ($tenant_id,$goods_spu){
                $query->where('tenant_id', $tenant_id)->where('goods_spu', $goods_spu);
            },true);

            $tenantGoodsService = new TenantGoodsService;
            $tenantGoodsService->addSelect($syst_goods_id,$tenant_id);

            Db::commit();
            return true;
        } catch (\Exception $exception) {
            Db::rollback();
            throw new Exception($exception->getMessage());
        }
    }

//    public function dealData($goods_spu,$notify_type){
//        $model = new externalGoodsModel();
//        $goods_result =  $model->where('goods_spu',$goods_spu)->field('id,is_sale')->find()->toArray();
//
//        try {
//            $attr_res = (new Goods)->goodsSpecPrice(['goods_spu'=>$goods_spu,'old_goods_spu'=>''])['data'];
//            $goods_res = (new Goods())->detail(['goods_spu'=>$goods_spu,'old_goods_spu'=>$goods_spu])['data'];
//        }catch (\Exception $exception){
////            dd($exception->getMessage());
//            //捕获到接口异常，可能没有数据。暂时下架处理
//            //$this->notifyGoodsUnShelveBySPU($goods_spu);
//
//            $model = (new externalGoodsModel)->where('goods_spu',$goods_spu)->find();
//            $model->is_sale = 0;//下架
//            $model->save();
//
//            $tenantGoodsModel = new tenantGoodsModel();
//            $tenantGoodsModel->where('goods_spu',$spu_id)->save(['is_sale'=>0]);
//
//
//            return $exception->getMessage();
//        }
//
//
//    }

    //删除商品
    public function deleteGoods($id)
    {
        Db::startTrans();
        try {
            //获取商品信息
            $goodsModel = new externalGoodsModel();
            $goods_info = $goodsModel->findBy($id);

            if(empty($goods_info)){
                throw new Exception('商品不存在');
            }

            $goods_spu = $goods_info['goods_spu'];
            
            //删除商品
            //$goodsModel->deleteBy($id, true);
            Db::table('db_syst_sync_goods')->where('id', $id)->delete();

            //删除商品属性
            Db::table('db_syst_sync_goods_attribute')->where('goods_id', $id)->delete();

            //删除商品规格
            Db::table('db_syst_sync_goods_rule')->where('goods_id', $id)->delete();


            //删除供应商的商品
            $tenantGoodsModel = new tenantGoodsModel();
            $tenantGoodsAttrModel = new tenantGoodsAttrModel();
            $tenantGoodsRuleModel = new tenantGoodsRuleModel();

            //通过spu删除供应商商品
            $tenantGoodsModel::destroy(function($query) use ($goods_spu){
                $query->where('goods_spu', $goods_spu);
            }, true);

            //删除供应商商品属性
            $tenantGoodsAttrModel::destroy(function($query) use ($goods_spu){
                $query->where('goods_spu', $goods_spu);
            }, true);


            //删除供应商商品规格
            $tenantGoodsRuleModel::destroy(function($query) use ($goods_spu){
                $query->where('goods_spu', $goods_spu);
            }, true);


            //如果是候鸟商品,需要取消订阅
            if(1 == $goods_info['supplier_id']){
                $this->goodsSubscribe($goods_spu, 2);
            }

            Db::commit();
            return true;
        } catch (\Exception $exception) {
            Db::rollback();

            return $exception->getMessage();
            //throw new Exception($exception->getMessage());
        }
    }
}